package org.jeecg.modules.demo.carallowance.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.carallowance.entity.CarAllowance;
import org.jeecg.modules.demo.carallowance.service.ICarAllowanceService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.spcFlow.entity.SpcFlowMaster;
import org.jeecg.modules.demo.spcFlow.entity.SpcFlowMasterDetail;
import org.jeecg.modules.demo.spcFlow.service.ISpcFlowMasterDetailService;
import org.jeecg.modules.demo.spcFlow.service.ISpcFlowMasterService;
import org.jeecg.modules.demo.spcFlowReport.entity.SpcFlowReport;
import org.jeecg.modules.demo.spcFlowReport.service.ISpcFlowReportService;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: car_allowance
 * @Author: jeecg-boot
 * @Date:   2025-06-24
 * @Version: V1.0
 */
@Api(tags="car_allowance")
@RestController
@RequestMapping("/carallowance/carAllowance")
@Slf4j
public class CarAllowanceController extends JeecgController<CarAllowance, ICarAllowanceService> {
	@Autowired
	private ICarAllowanceService carAllowanceService;
	 @Autowired
	 private ISpcFlowMasterDetailService spcFlowMasterDetailService;
	 @Autowired
	 private ISpcFlowMasterService spcFlowMasterService;
	 @Autowired
	 private ISpcFlowReportService spcFlowReportService;

	/**
	 * 分页列表查询
	 *
	 * @param carAllowance
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "car_allowance-分页列表查询")
	@ApiOperation(value="car_allowance-分页列表查询", notes="car_allowance-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CarAllowance>> queryPageList(CarAllowance carAllowance,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CarAllowance> queryWrapper = QueryGenerator.initQueryWrapper(carAllowance, req.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		queryWrapper.and(wrapper -> wrapper.eq("sys_org_code", sysUser.getOrgCode()).or()
				.eq("reviewed_by",sysUser.getUsername()).or().eq("create_by",sysUser.getUsername()));
		Page<CarAllowance> page = new Page<CarAllowance>(pageNo, pageSize);
		IPage<CarAllowance> pageList = carAllowanceService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param carAllowance
	 * @return
	 */
	@AutoLog(value = "car_allowance-添加")
	@ApiOperation(value="car_allowance-添加", notes="car_allowance-添加")
	//@RequiresPermissions("carallowance:car_allowance:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CarAllowance carAllowance) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//自动生成产量登记单编号
		String str = carAllowanceService.getMaxCode();
		Map<String,String> map = new HashMap<>();
		map.put("maxCode",str==null?null:str);
		String name = "CB_";
		String resultCode = generateOddUtil.createCode(map,name);
		carAllowance.setDocumentNumber(resultCode);
		carAllowance.setCreateTime(new Date());
		carAllowance.setDocumentStatus(0);
		carAllowance.setSysOrgCode(sysUser.getOrgCode());
		carAllowance.setCreateBy(sysUser.getUsername());


		SpcFlowMaster spcFlowMaster = spcFlowMasterService.getById(carAllowance.getFlowNum());
		SpcFlowMasterDetail spcFlowMasterDetail =
				spcFlowMasterDetailService.getOneByFlowIdAndStep
						(carAllowance.getFlowStep()+1,carAllowance.getFlowNum());
		if(spcFlowMasterDetail != null){
			carAllowance.setReviewedBy(spcFlowMasterDetail.getReviewedById());
			carAllowance.setFlowStep(spcFlowMasterDetail.getAuditStep());
		}else{
			if(carAllowance.getFlowStep() == null){
				carAllowance.setFlowStep("1");
			}
			SpcFlowMasterDetail spcFlowMasterDetaily =
					spcFlowMasterDetailService.getOneByFlowIdAndStep
							(carAllowance.getFlowStep(),carAllowance.getFlowNum());
			carAllowance.setReviewedBy(spcFlowMasterDetaily.getReviewedById());
			carAllowance.setFlowStep(spcFlowMasterDetaily.getAuditStep());
		}
		carAllowanceService.save(carAllowance);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param carAllowance
	 * @return
	 */
	@AutoLog(value = "car_allowance-编辑")
	@ApiOperation(value="car_allowance-编辑", notes="car_allowance-编辑")
	//@RequiresPermissions("carallowance:car_allowance:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CarAllowance carAllowance) {
		SpcFlowMaster spcFlowMaster = spcFlowMasterService.getById(carAllowance.getFlowNum());
		SpcFlowMasterDetail spcFlowMasterDetail =
				spcFlowMasterDetailService.getOneByFlowIdAndStep
						(carAllowance.getFlowStep()+1,carAllowance.getFlowNum());
		if(spcFlowMasterDetail != null){
			carAllowance.setReviewedBy(spcFlowMasterDetail.getReviewedById());
			carAllowance.setFlowStep(spcFlowMasterDetail.getAuditStep());
		}else{
			if(carAllowance.getFlowStep() == null){
				carAllowance.setFlowStep("1");
			}
			SpcFlowMasterDetail spcFlowMasterDetaily =
					spcFlowMasterDetailService.getOneByFlowIdAndStep
							(carAllowance.getFlowStep(),carAllowance.getFlowNum());
			carAllowance.setReviewedBy(spcFlowMasterDetaily.getReviewedById());
			carAllowance.setFlowStep(spcFlowMasterDetaily.getAuditStep());

		}
		if(spcFlowMaster != null){
			spcFlowMaster.setUsestate("1");
			spcFlowMasterService.updateById(spcFlowMaster);
		}
		carAllowanceService.updateById(carAllowance);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "car_allowance-通过id删除")
	@ApiOperation(value="car_allowance-通过id删除", notes="car_allowance-通过id删除")
	//@RequiresPermissions("carallowance:car_allowance:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		carAllowanceService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "car_allowance-批量删除")
	@ApiOperation(value="car_allowance-批量删除", notes="car_allowance-批量删除")
	//@RequiresPermissions("carallowance:car_allowance:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.carAllowanceService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "car_allowance-通过id查询")
	@ApiOperation(value="car_allowance-通过id查询", notes="car_allowance-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CarAllowance> queryById(@RequestParam(name="id",required=true) String id) {
		CarAllowance carAllowance = carAllowanceService.getById(id);
		if(carAllowance==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(carAllowance);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param carAllowance
    */
    //@RequiresPermissions("carallowance:car_allowance:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CarAllowance carAllowance) {
        return super.exportXls(request, carAllowance, CarAllowance.class, "car_allowance");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("carallowance:car_allowance:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CarAllowance.class);
    }

	 @RequestMapping(value = "/carAllowjShenhe", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> dailyShenhe(@RequestBody CarAllowance carAllowance) {

		 QueryWrapper<SpcFlowMasterDetail> spcFlowMasterQueryWrapper = new QueryWrapper<SpcFlowMasterDetail>();
		 spcFlowMasterQueryWrapper.eq("flow_no",carAllowance.getFlowNum());
		 spcFlowMasterQueryWrapper.orderByAsc("audit_step");
		 List<SpcFlowMasterDetail> spcFlowMasterDetailList = spcFlowMasterDetailService.list(spcFlowMasterQueryWrapper);
		 SpcFlowReport spcFlowReport = new SpcFlowReport();
		 SpcFlowMasterDetail spcFlowMasterDetailOldReview =
				 spcFlowMasterDetailService.getOneByFlowIdAndStep
						 (carAllowance.getFlowStep(),carAllowance.getFlowNum());
		 spcFlowReport.setCreateBy(spcFlowMasterDetailOldReview.getCreateBy());
		 if(carAllowance.getFlowNum() == null){
			 return Result.error("未选单据流转流程，请选择！");
		 }
		 if(carAllowance.getFlowNum() != null){
			 if(carAllowance.getFlowStep() != null){
				 if(spcFlowMasterDetailList != null && spcFlowMasterDetailList.size() != 0){

					 SpcFlowMasterDetail spcFlowMasterDetail =
							 spcFlowMasterDetailService.getOneByFlowIdAndStep
									 (String.valueOf(Integer.parseInt(carAllowance.getFlowStep())+1),carAllowance.getFlowNum());
					 if(spcFlowMasterDetail!=null){
						 carAllowance.setDocumentStatus(spcFlowMasterDetail.getFlowStatus());
						 carAllowance.setFlowStep(spcFlowMasterDetail.getAuditStep());
						 carAllowance.setReviewedTime(new Date());
						 carAllowance.setReviewedBy(spcFlowMasterDetail.getReviewedById());
					 }else{
						 SpcFlowMasterDetail spcFlowMasterDetailOld =
								 spcFlowMasterDetailService.getOneByFlowIdAndStep
										 (carAllowance.getFlowStep(),carAllowance.getFlowNum());
						 carAllowance.setDocumentStatus(1);
						 carAllowance.setReviewedTime(new Date());
						 carAllowance.setReviewedBy(spcFlowMasterDetailOld.getReviewedById());
					 }

					 //记录到审核记录表中

					 spcFlowReport.setAuditTime(new Date());
					 //spcFlowReport.setCreateBy(spcDailyPlan.getReviewedBy());
					 spcFlowReport.setDocumentCode(carAllowance.getDocumentNumber());
					 spcFlowReport.setFlowAction("审核成功！");
					 spcFlowReport.setStepNum(Integer.parseInt(carAllowance.getFlowStep()));
					 spcFlowReportService.save(spcFlowReport);

					 carAllowanceService.updateById(carAllowance);

					 return Result.ok("审核成功!");
				 }
			 }else{
				 if(carAllowance.getDocumentStatus() == 0){
					 carAllowance.setDocumentStatus(spcFlowMasterDetailList.get(0).getFlowStatus());
					 carAllowance.setFlowStep(spcFlowMasterDetailList.get(0).getAuditStep());
					 carAllowance.setReviewedBy(spcFlowMasterDetailList.get(0).getReviewedById());
					 carAllowance.setReviewedTime(new Date());
					 carAllowanceService.updateById(carAllowance);
					 //SpcFlowReport spcFlowReport = new SpcFlowReport();
					 spcFlowReport.setAuditTime(new Date());
					 //spcFlowReport.setCreateBy(spcDailyPlan.getReviewedBy());
					 spcFlowReport.setDocumentCode(carAllowance.getDocumentNumber());
					 spcFlowReport.setFlowAction("审核成功！");
					 spcFlowReport.setStepNum(Integer.parseInt(carAllowance.getFlowStep()));
					 spcFlowReportService.save(spcFlowReport);
					 return Result.ok("审核成功!");
				 }
			 }
		 }
		 return null;
	 }


	 //弃审
	 @RequestMapping(value = "/cancelShenhe", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> cancelShenhe(@RequestBody CarAllowance carAllowance) {
		 if (carAllowance.getDocumentStatus() != 0){
			 carAllowance.setDocumentStatus(0);
			 carAllowance.setReviewedTime(null);
			 carAllowance.setFlowStep("1");
			 SpcFlowMasterDetail spcFlowMasterDetailOld =
					 spcFlowMasterDetailService.getOneByFlowIdAndStep
							 (carAllowance.getFlowStep(),carAllowance.getFlowNum());
			 if(spcFlowMasterDetailOld != null){
				 carAllowance.setReviewedBy(spcFlowMasterDetailOld.getReviewedById());
			 }

			 SpcFlowReport spcFlowReport = new SpcFlowReport();
			 spcFlowReport.setCreateTime(new Date());
			 spcFlowReport.setCreateBy(carAllowance.getReviewedBy());
			 spcFlowReport.setDocumentCode(carAllowance.getDocumentNumber());
			 spcFlowReport.setFlowAction("弃审成功！");
			 spcFlowReport.setStepNum(Integer.parseInt(carAllowance.getFlowStep()));
			 spcFlowReport.setRemark(carAllowance.getRemark());
			 spcFlowReportService.save(spcFlowReport);



			 carAllowanceService.updateById(carAllowance);
		 }
		 return Result.OK("弃审成功!");
	 }


	 //流程步骤显示
	 @RequestMapping(value="/flowstepdisplay",method={RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> flowstepdisplay(@RequestBody CarAllowance carAllowance){
		 //下一步审核
		 SpcFlowMasterDetail spcFlowMasterDetail =
				 spcFlowMasterDetailService.getOneByFlowIdAndStep
						 (String.valueOf(Integer.parseInt(carAllowance.getFlowStep())+1),carAllowance.getFlowNum());
		 //当前审核
		 SpcFlowMasterDetail spcFlowMasterDetailastStep =
				 spcFlowMasterDetailService.getOneByFlowIdAndStep
						 (String.valueOf(Integer.parseInt(carAllowance.getFlowStep())),carAllowance.getFlowNum());

		 Map stepMap = new HashMap();
		 if(spcFlowMasterDetail != null){
			 //stepMap.put("dqshenheren",spcFlowMasterDetail.getCreateBy());
			 stepMap.put("dqstepshenheren",spcFlowMasterDetailastStep.getReviewedById());
			 //stepMap.put("nextstep",spcFlowMasterDetail.getAuditStep());
			 stepMap.put("dqstep",spcFlowMasterDetailastStep.getAuditStep());
		 }else{
			 stepMap.put("dqstepshenheren",spcFlowMasterDetailastStep.getReviewedById());
			 stepMap.put("dqstep",spcFlowMasterDetailastStep.getAuditStep());
		 }
		 QueryWrapper<SpcFlowMasterDetail> spcFlowMasterDetailQueryWrapper = new QueryWrapper<SpcFlowMasterDetail>();
		 spcFlowMasterDetailQueryWrapper.eq("flow_no",carAllowance.getFlowNum());
		 spcFlowMasterDetailQueryWrapper.orderByAsc("audit_step");
		 List<SpcFlowMasterDetail> spcFlowMasterDetailList = spcFlowMasterDetailService.list(spcFlowMasterDetailQueryWrapper);
		 stepMap.put("spcflowlist",spcFlowMasterDetailList);
		 String s = JSON.toJSONString(stepMap);
		 return Result.OK("",s);
	 }



}
